package com.system.honour.service.impl;

import com.system.honour.common.ResultDTO;
import com.system.honour.dto.LoginUser;
import com.system.honour.entity.SysPermission;
import com.system.honour.entity.SysUser;
import com.system.honour.service.PermissionService;
import com.system.honour.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Autowired
	private UserService userService;
	@Autowired
	private PermissionService permissionService;
	/**
	 * 自定义用户校验方法
	 * @param username
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		SysUser user = userService.getUser(username);
		if (user==null){
			throw new AuthenticationCredentialsNotFoundException("用户名不存在");
		}else if (user.getStatus()==2){
			throw new LockedException("用户被锁定,请联系管理员");
		}

		//封装信息
		LoginUser loginUser = new LoginUser();
		BeanUtils.copyProperties(user,loginUser);
		List<SysPermission> permissionList = permissionService.getListByUserId(user.getId());
		loginUser.setPermissions(permissionList);
		return loginUser;
	}
}
